<template>
  <div id="app">
    <div class="chat-container">
      <!-- 聊天记录区域 -->
      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.type]"
        >
          <div class="message-content">
            <div class="avatar">
              <img 
                :src="message.type === 'ai' ? '/ai-avatar.svg' : '/user-avatar.svg'" 
                :alt="message.type === 'ai' ? 'AI' : 'User'"
                @error="handleImageError"
              />
            </div>
            <div class="message-bubble">
              <div class="message-text" v-html="formatMessage(message.content)" :class="{ 'typing-effect': message.isTyping }"></div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 加载指示器 -->
        <div v-if="isLoading" class="message ai">
          <div class="message-content">
            <div class="avatar">
              <img src="/ai-avatar.svg" alt="AI" @error="handleImageError" />
            </div>
            <div class="message-bubble">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input-container">
        <div class="input-wrapper">
          <textarea
            v-model="userInput"
            @keydown.enter.prevent="sendMessage"
            @keydown.enter.shift.exact="sendMessage"
            placeholder="请输入您的问题..."
            class="chat-input"
            :disabled="isLoading"
            ref="inputRef"
          ></textarea>
          <button 
            @click="sendMessage" 
            class="send-button"
            :disabled="!userInput.trim() || isLoading"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M22 2L11 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M22 2L15 22L11 13L2 9L22 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'

export default {
  name: 'App',
  setup() {
    const messages = ref([])
    const userInput = ref('')
    const isLoading = ref(false)
    const messagesContainer = ref(null)
    const inputRef = ref(null)

    // AI开场白
    const aiGreeting = {
      type: 'ai',
      content: '您好！我是您的专属健康管家。在制定方案前，我需要先了解您的身体状况。您方便用30秒描述最近一次运动后的身体感受吗？',
      timestamp: new Date()
    }

    // 初始化消息
    onMounted(() => {
      messages.value = [aiGreeting]
      scrollToBottom()
    })

    // 发送消息
    const sendMessage = async () => {
      if (!userInput.value.trim() || isLoading.value) return

      const userMessage = {
        type: 'user',
        content: userInput.value.trim(),
        timestamp: new Date()
      }

      messages.value.push(userMessage)
      const currentInput = userInput.value.trim()
      userInput.value = ''
      isLoading.value = true

      await nextTick()
      scrollToBottom()

      try {
        await sendSSEMessage(currentInput)
      } catch (error) {
        console.error('发送消息失败:', error)
        messages.value.push({
          type: 'ai',
          content: '抱歉，我遇到了一些问题。请稍后再试。',
          timestamp: new Date()
        })
      } finally {
        isLoading.value = false
        await nextTick()
        scrollToBottom()
        inputRef.value?.focus()
      }
    }

    // SSE发送消息
    const sendSSEMessage = (message) => {
      return new Promise((resolve, reject) => {
        const eventSource = new EventSource(`http://localhost:8123/api/ai/manus/chat?message=${encodeURIComponent(message)}`)

        eventSource.onmessage = (event) => {
          const content = event.data
          if (content) {
            // 新建一条AI消息
            const aiMessage = {
              type: 'ai',
              content: '',
              isTyping: true,
              timestamp: new Date()
            }
            messages.value.push(aiMessage)
            startTypingEffect(aiMessage, content)
          }
        }

        eventSource.onerror = (error) => {
          console.log('SSE连接错误:', error)
          eventSource.close()
          isLoading.value = false
          messages.value.push({
            type: 'ai',
            content: '抱歉，连接出现问题。请稍后再试。',
            timestamp: new Date()
          })
          reject(error)
        }

        eventSource.addEventListener('end', () => {
          console.log('SSE流结束')
          eventSource.close()
          resolve()
        })

        // 设置超时处理
        setTimeout(() => {
          if (eventSource.readyState !== EventSource.CLOSED) {
            console.log('SSE连接超时，关闭连接')
            eventSource.close()
            resolve()
          }
        }, 30000) // 30秒超时
      })
    }

    // 打字机效果
    const startTypingEffect = (message, fullContent) => {
      const typeSpeed = 30 // 每个字符的延迟时间（毫秒）
      let currentIndex = 0
      const typeNextChar = () => {
        if (currentIndex < fullContent.length && message.isTyping) {
          message.content = fullContent.substring(0, currentIndex + 1)
          currentIndex++
          scrollToBottom()
          setTimeout(typeNextChar, typeSpeed)
        } else {
          message.isTyping = false
          message.content = fullContent
          scrollToBottom()
        }
      }
      typeNextChar()
    }

    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
      })
    }

    // 格式化消息内容（支持换行）
    const formatMessage = (content) => {
      return content.replace(/\n/g, '<br>')
    }

    // 格式化时间
    const formatTime = (timestamp) => {
      return new Date(timestamp).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 处理图片加载错误
    const handleImageError = (event) => {
      event.target.style.display = 'none'
    }

    return {
      messages,
      userInput,
      isLoading,
      messagesContainer,
      inputRef,
      sendMessage,
      formatMessage,
      formatTime,
      handleImageError
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  height: 100vh;
  overflow: hidden;
}

#app {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-container {
  width: 100%;
  max-width: 800px;
  height: 100vh;
  background: white;
  border-radius: 0;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f8f9fa;
}

.message {
  margin-bottom: 20px;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.ai {
  justify-content: flex-start;
}

.message-content {
  display: flex;
  align-items: flex-start;
  max-width: 70%;
}

.message.user .message-content {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  margin: 0 10px;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-bubble {
  background: white;
  padding: 12px 16px;
  border-radius: 18px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
}

.message.user .message-bubble {
  background: #007bff;
  color: white;
}

.message.ai .message-bubble {
  background: white;
  color: #333;
}

.message-text {
  line-height: 1.5;
  word-wrap: break-word;
}

.message-text.typing-effect::after {
  content: '|';
  animation: blink 1s infinite;
  color: #007bff;
  font-weight: bold;
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
  margin-top: 4px;
}

.chat-input-container {
  padding: 20px;
  background: white;
  border-top: 1px solid #e9ecef;
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 10px;
}

.chat-input {
  flex: 1;
  border: 2px solid #e9ecef;
  border-radius: 20px;
  padding: 12px 16px;
  font-size: 14px;
  resize: none;
  min-height: 44px;
  max-height: 120px;
  outline: none;
  transition: border-color 0.3s;
  font-family: inherit;
}

.chat-input:focus {
  border-color: #007bff;
}

.chat-input:disabled {
  background: #f8f9fa;
  cursor: not-allowed;
}

.send-button {
  width: 44px;
  height: 44px;
  border: none;
  border-radius: 50%;
  background: #007bff;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  flex-shrink: 0;
}

.send-button:hover:not(:disabled) {
  background: #0056b3;
  transform: scale(1.05);
}

.send-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #007bff;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    max-width: 100%;
    border-radius: 0;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .chat-messages {
    padding: 15px;
  }
  
  .chat-input-container {
    padding: 15px;
  }
}
</style>
